<?
require_once("dbdException.php");

class dbdLoader
{
	const DEFAULT_CONTROLLER_DIR = "controllers";
	const DEFAULT_MODEL_DIR = "models";

	private static $instance = null;
	private $include_paths = array();
	private $controller_dir = null;
	private $model_dir = null;

	private function __construct()
	{
		$this->init();
	}

	private function init()
	{
		foreach (explode(":", trim(ini_get("include_path"), ":")) as $p)
			$this->register($p);
		if (!$this->controller_dir)
			$this->controller_dir = self::DEFAULT_CONTROLLER_DIR;
		if (!$this->model_dir)
			$this->model_dir = self::DEFAULT_MODEL_DIR;
	}

	private function register($path)
	{
		if (empty($path))
			return;
		if (substr($path, -1) != DBD_DS)
			$path .= DBD_DS;
		if (!in_array($path, $this->include_paths))
			$this->include_paths[] = $path;
		ini_set("include_path", ini_get("include_path").":".$path);
	}

	public static function getInstance()
	{
		if (self::$instance === null)
			self::$instance = new self();
		return self::$instance;
	}

	public static function addPath($path)
	{
		self::getInstance()->register($path);
	}

	public static function getPaths()
	{
		return self::getInstance()->include_paths;
	}

	public static function setControllerDir($dir)
	{
		self::getInstance()->controller_dir = $dir;
	}

	public static function setModelDir($dir)
	{
		self::getInstance()->model_dir = $dir;
	}

	public static function getControllerDir()
	{
		return self::getInstance()->controller_dir;
	}

	public static function getModelDir()
	{
		return self::getInstance()->model_dir;
	}

	public static function load($file)
	{
		$paths = self::getPaths();
		if (in_array($file, get_included_files()))
		{
			return true;
		}
		else
		{
			foreach ($paths as $p)
			{
				if (file_exists($p.$file))
				{
				    require_once($p.$file);
					return true;
				}
			}
		}
		throw new dbdException("File (".$file.") could not be found!\n\nPATHS:\n".implode("\n", $paths));
	}

	public static function loadClass($class)
	{
		$file = $class.".php";
		try
		{
			self::load($file);
		}
		catch (dbdException $e)
		{
			throw $e;
		}
	}
}

function __autoload($class)
{
	dbdLoader::loadClass($class);
}
?>